'use strict';
var express = require('express');
var co = require('co');
var router = express.Router();
var daoHelper = require('../dao');
var commonUtil = require('../commonUtil'),
    pathVarRegx = /\/view-([^/]+)\/?/;

/* GET home page. */
router.get('/', co.wrap(function* (req, res, next) {
    var mainMenu = {}, ifMenus = {}, result = [], dao, pathInfo = pathVarRegx.exec(req.originalUrl),
        ifs, subIfs, ifDetails;

    if(!pathInfo){
        res.render('error', {
            message: 'invalid path',
            error: req.originalUrl
        });
        return;
    }


    dao = daoHelper.getDao(pathInfo[1]);
    try{
        ifs = yield dao.getInterfaces(0);
        commonUtil.each(ifs, function(_, ifObj){
            ifObj = ifObj.toObject();
            ifObj.ifs = [];
            mainMenu[ifObj.interfaceId] = ifObj;
            result.push(ifObj);
        });

        subIfs = yield dao.getInterfaces(1);
        commonUtil.each(subIfs, function(_, ifObj){
            ifObj = ifObj.toObject();
            ifMenus[ifObj.interfaceId] = ifObj;
            mainMenu[ifObj.parentId] && mainMenu[ifObj.parentId].ifs.push(ifObj);
        });

        ifDetails = yield dao.getAllDetail();
        commonUtil.each(ifDetails, function(_, ifDetail){
            ifDetail = ifDetail.toObject();
            ifMenus[ifDetail.interfaceId].detailInfo = ifDetail;
        });
    }catch(e){
        console.error(e);
    }


    res.render('index', {list : result, apps : req.authApps, appName : pathInfo[1]|| 'appInterface'});

}));

router.get('/getIf/:id', function (req, res, next) {
    var result, id = req.params.id, dao, pathInfo = pathVarRegx.exec(req.originalUrl);
    if(!pathInfo){
        res.render('error', {
            message: 'invalid path',
            error: req.originalUrl
        });
        return;
    }

    dao = daoHelper.getDao(pathInfo[1]);

    dao.getModuleById(id).then(function(m){
        result = m.toObject();
        return dao.getInterfaceById(id);
    }).then(function(i){
        result.detailInfo = i;
        return result;
    }).then(function(){
        res.end(JSON.stringify({suc : true, result : result }));
    }).then(null, function(err){
        res.end(JSON.stringify({suc : false, err : err}));
    });
});


module.exports = router;
